<template>
  <div class="appointment-container">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">预约管理</span>
          <div class="header-controls">
            <el-input
              v-model="searchQuery"
              placeholder="请输入学员姓名或教练姓名"
              style="width: 220px; margin-right: 15px;"
              clearable
              @input="debouncedSearch"
              @clear="fetchAppointments"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select
              v-model="statusFilter"
              placeholder="请选择状态"
              style="width: 130px; margin-right: 15px;"
              @change="handleStatusFilterChange"
            >
              <el-option label="全部" value=""></el-option>
              <el-option label="未确认" value="PENDING"></el-option>
              <el-option label="已确认" value="CONFIRMED"></el-option>
            </el-select>
          </div>
        </div>
      </template>

      <el-table
        :data="filteredAppointments"
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        border
      >
        <el-table-column label="序号" width="60" align="center">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="student_name" label="学员姓名" min-width="100" />
        <el-table-column prop="coach_name" label="教练姓名" min-width="100" />
        <el-table-column prop="program_name" label="科目名称" min-width="120" />
        <el-table-column prop="appointment_date" label="预约日期" min-width="110" />
        <el-table-column prop="start_time" label="开始时间" min-width="100" />
        <el-table-column prop="end_time" label="结束时间" min-width="100" />
        <el-table-column prop="status_text" label="状态" min-width="90">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 'PENDING' ? 'warning' :
                     scope.row.status === 'CONFIRMED' ? 'success' : 'info'">
              {{ scope.row.status_text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="scope">
            <div class="operation-cell">
              <div v-if="scope.row.status === 'PENDING'">
                <el-button size="small" type="success" @click="confirmAppointment(scope.row)">通过</el-button>
                <el-button size="small" type="warning" @click="cancelAppointment(scope.row)">取消</el-button>
              </div>
              <div v-else-if="scope.row.status === 'CONFIRMED'">
                <el-button size="small" type="warning" @click="cancelAppointment(scope.row)">取消</el-button>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import requestUtil from '@/util/request.js';
import debounce from 'lodash/debounce';

// 数据相关
const appointments = ref([]);
const students = ref([]);
const coaches = ref([]);
const programs = ref([]);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const statusFilter = ref(''); // 状态筛选条件

// 工具函数
const timeStringToSeconds = (str) => {
  const [h, m, s] = str.split(':').map(Number);
  return h * 3600 + m * 60 + s;
};

const secondsToTimeString = (seconds) => {
  const h = String(Math.floor(seconds / 3600)).padStart(2, '0');
  const m = String(Math.floor((seconds % 3600) / 60)).padStart(2, '0');
  const s = String(seconds % 60).padStart(2, '0');
  return `${h}:${m}:${s}`;
};

// 将预约的日期和时间组合成训练表需要的datetime格式
const combineDateTime = (date, time) => {
  return `${date} ${time}`;
};

// 状态文本映射
const getStatusText = (status) => {
  const statusMap = {
    'PENDING': '未确认',
    'CONFIRMED': '已确认',
    'CANCELLED': '已取消'
  };
  return statusMap[status] || status;
};

// 数据获取函数
const fetchPrograms = async () => {
  try {
    const res = await requestUtil.get('/program/msg', {
      page: 1,
      page_size: 100
    });

    if (res.data?.status === 200) {
      programs.value = res.data.data || [];
    } else {
      programs.value = [];
      ElMessage.error('获取培训项目失败: ' + (res.data?.message || '未知错误'));
    }
  } catch (error) {
    if (error.response?.status === 422) {
      try {
        const res = await requestUtil.get('/program/msg');
        if (res.data?.status === 200) {
          programs.value = res.data.data || [];
        }
      } catch (fallbackError) {
        programs.value = [];
        ElMessage.error('获取培训项目失败: ' + (fallbackError.response?.data?.message || fallbackError.message));
      }
    } else {
      programs.value = [];
      ElMessage.error('获取培训项目异常: ' + (error.response?.data?.message || error.message));
    }
  }
};

const fetchStudents = async () => {
  const res = await requestUtil.get('/student/msg');
  if (res.data?.status === 200) {
    students.value = res.data.data;
  }
};

const fetchCoaches = async () => {
  const res = await requestUtil.get('/coach/msg');
  if (res.data?.status === 200) {
    coaches.value = res.data.data;
  }
};

const fetchAppointments = async () => {
  const res = await requestUtil.get('/appointment/msg', {
    page: currentPage.value,
    page_size: pageSize.value
  });

  if (res.data?.status === 200) {
    // 根据状态筛选条件过滤数据
    let filteredData = res.data.data;

    // 如果选择了状态筛选条件，则进行筛选
    if (statusFilter.value) {
      filteredData = filteredData.filter(app => app.status === statusFilter.value);
    } else {
      // 如果没有选择筛选条件，默认只显示未确认和已确认的预约
      filteredData = filteredData.filter(app =>
        app.status === 'PENDING' || app.status === 'CONFIRMED'
      );
    }

    appointments.value = filteredData.map(app => {
      const student = students.value.find(s => s.student_id === app.student_id);
      const coach = coaches.value.find(c => c.coach_id === app.coach_id);
      const program = programs.value.find(p => p.program_id === app.program_id);
      return {
        ...app,
        student_name: student?.fullname || '未知学员',
        coach_name: coach?.fullname || '未知教练',
        program_name: program?.name || '未知科目',
        start_time: secondsToTimeString(app.start_time),
        end_time: secondsToTimeString(app.end_time),
        status_text: getStatusText(app.status) // 添加中文状态文本
      };
    });
    total.value = res.data.total || 0;
  }
};

// 搜索相关
const filteredAppointments = computed(() => {
  if (!searchQuery.value.trim()) return appointments.value;
  return appointments.value.filter(app =>
    app.student_name.includes(searchQuery.value) ||
    app.coach_name.includes(searchQuery.value)
  );
});

const debouncedSearch = debounce(fetchAppointments, 300);

// 分页相关
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchAppointments();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchAppointments();
};

// 状态筛选变化处理
const handleStatusFilterChange = () => {
  currentPage.value = 1; // 重置到第一页
  fetchAppointments();
};

// 确认预约并创建训练记录
const confirmAppointment = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要确认这个预约吗？`,
      '确认预约',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 更新预约状态为CONFIRMED
    const res = await requestUtil.put(`/appointment/update/${row.appointment_id}`, {
      ...row,
      status: 'CONFIRMED',
      start_time: timeStringToSeconds(row.start_time),
      end_time: timeStringToSeconds(row.end_time),
      program_id: row.program_id
    });

    if (res.data?.status === 200) {
      // 如果原状态是PENDING，则创建或更新训练记录
      if (row.status === 'PENDING') {
        try {
          // 先检查学生是否已有该项目的训练记录
          const existingTrainingRes = await requestUtil.get('/student_training/trainings', {
            student_id: row.student_id,
            program_id: row.program_id
          });

          let trainingResult;

          if (existingTrainingRes.data?.status === 200 && existingTrainingRes.data.data?.length > 0) {
            // 如果存在现有记录，则更新第一条记录
            const existingTraining = existingTrainingRes.data.data[0];

            // 使用正确的PUT路径更新训练记录
            trainingResult = await requestUtil.put(`/student_training/trainings/update/${existingTraining.training_id}`, {
              coach_id: row.coach_id,
              start_time: combineDateTime(row.appointment_date, row.start_time),
              end_time: combineDateTime(row.appointment_date, row.end_time),
              status: 'SCHEDULED',
              rating: 1,
              feedback: '',
              content: '管理员通过'
            });

            if (trainingResult.data?.status === 200) {
              ElMessage.success('预约已确认，现有训练记录已更新');
            } else {
              ElMessage.warning('预约已确认，但训练记录更新失败: ' + (trainingResult.data?.message || '未知错误'));
            }
          } else {
            // 如果不存在现有记录，则创建新记录
            trainingResult = await requestUtil.post('/student_training/trainings/add', {
              student_id: row.student_id,
              coach_id: row.coach_id,
              program_id: row.program_id,
              start_time: combineDateTime(row.appointment_date, row.start_time),
              end_time: combineDateTime(row.appointment_date, row.end_time),
              status: 'SCHEDULED', // 训练状态设为已安排
              rating: 1,
              feedback: '',
              content: '管理员通过'
            });

            if (trainingResult.data?.status === 201) {
              ElMessage.success('预约已确认，训练记录已创建');
            } else {
              ElMessage.warning('预约已确认，但训练记录创建失败: ' + (trainingResult.data?.message || '未知错误'));
            }
          }
        } catch (trainingError) {
          ElMessage.warning('预约已确认，但训练记录操作失败: ' + (trainingError.response?.data?.message || trainingError.message));
        }
      } else {
        ElMessage.success('预约已确认');
      }

      await fetchAppointments();
    } else {
      ElMessage.error(res.data?.message || '确认失败');
    }
  } catch (error) {
    if (error === 'cancel' || error === 'close') {
      ElMessage.info('已取消操作');
      return;
    }
    ElMessage.error(error.response?.data?.message || '确认失败');
  }
};



const cancelAppointment = async (row) => {
  try {
    await ElMessageBox.confirm(
        '确定要取消这个预约吗？',
        '取消预约',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    const res = await requestUtil.put(`/appointment/update/${row.appointment_id}`, {
      ...row,
      status: 'CANCELLED',
      start_time: timeStringToSeconds(row.start_time),
      end_time: timeStringToSeconds(row.end_time),
      program_id: row.program_id
    });

    if (res.data?.status === 200) {
      ElMessage.success('预约已取消');
      await fetchAppointments();
    } else {
      ElMessage.error(res.data?.message || '取消失败');
    }
  } catch (error) {
    if (error === 'cancel' || error === 'close') {
      ElMessage.info('已取消操作');
      return;
    }
    ElMessage.error(error.response?.data?.message || '取消失败');
  }
};

// 生命周期
onMounted(async () => {
  await Promise.all([
    fetchStudents(),
    fetchCoaches(),
    fetchPrograms()
  ]);
  await fetchAppointments();
});
</script>

<style scoped>
.appointment-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
}

.main-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-controls {
  display: flex;
  align-items: center;
}

.operation-cell {
  display: flex;
  gap: 5px;
  justify-content: center;
}

.operation-cell .el-button {
  margin-right: 5px;
}

.operation-cell .el-button:last-child {
  margin-right: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table th) {
  font-weight: 600;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}
</style>
